package com.ymsoft.myerp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ymsoft.myerp.entity.Role;
import com.ymsoft.myerp.entity.User;
import com.ymsoft.myerp.entity.UserDetail;
import com.ymsoft.myerp.service.IRoleService;
import com.ymsoft.myerp.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by linziyu on 2019/2/9.
 */

@Component("MyUserDetailService")
@Slf4j
public class MyUserDetailService implements UserDetailsService {


    @Autowired
    private IUserService iUserService;

    @Autowired
    private IRoleService iRoleService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        grantedAuthorityList.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return "admin";
            }
        });
        log.info("{}", "传进来的名字" + s);
        log.info("{}", "验证。。。。。");

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", s);
        User user = iUserService.getOne(queryWrapper, false);
        if (user == null) {
            throw new UsernameNotFoundException("");
        }
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("username", s);
        Role role = iRoleService.getById(user.getRoleId());
        UserDetail userDetail = new UserDetail(user.getUsername(), user.getPassword(), role);
        return userDetail;

    }
}
